package org.jeecg.modules.solitaire_app.app.controller;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.AppSigner;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Slf4j
@Api(tags = "国际原油")
@RestController
@RequestMapping("/app/gjyyCon")
public class GjyyController {

    @Autowired
    RedisUtil redisUtil;

    /**
     * 国际原油-国际原油
     *
     * @return
     */
    @ApiOperation(value = "国际原油-国际原油", notes = "国际原油-国际原油")
    @GetMapping(value = "/getGjyy/{code}")
    public Result<?> getGjyy(@PathVariable String code) {

        Result<JSONObject> result = new Result<>();

        LocalDate currentDate = LocalDate.now();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

        //先判断有没有今天的数据
        String key = currentDate.format(formatter) + code;
        if (redisUtil.hasKey(key)) {
            JSONObject jsonObject = new JSONObject(redisUtil.get(key));
            result.setCode(200);
            result.setSuccess(true);
            result.setResult(jsonObject);
            return result;
        }

        String path = "https://jmgjyyjgcx.api.bdymkt.com/gjyycx/oil/price-inter/query";
        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.POST, path);
        request.setCredentials("2a1650d2b63c4a038b218c66e4157415", "52b2b81c99384292813f53f44fde5aca");

        // 设置header参数
        request.addHeaderParameter("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

        // 设置jsonBody参数
        String jsonBody = "code=" + code;
        request.setJsonBody(jsonBody);

        ApiExplorerClient client = new ApiExplorerClient(new AppSigner());

        try {
            ApiExplorerResponse response = client.sendRequest(request);
            // 返回结果格式为Json字符串
            JSONObject jsonObject = new JSONObject(response.getResult()).getJSONObject("data");

            redisUtil.set(key, jsonObject.toString());

            result.setCode(200);
            result.setSuccess(true);
            result.setResult(jsonObject);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setSuccess(false);
            result.setMessage("服务器响应失败");
            return result;
        }
    }

    /**
     * 国际原油-国际原油
     *
     * @return
     */
    @ApiOperation(value = "国际原油-国际原油", notes = "国际原油-国际原油")
    @GetMapping(value = "/getGjyyHis/{code}")
    public Result<?> getGjyyHis(@PathVariable String code) {

        Result<JSONArray> result = new Result<>();

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

        //先判断有没有今天的数据
        String key = currentDate.format(formatter) + "his" + "_" + code;
        if (redisUtil.hasKey(key)) {
            JSONArray jsonArray = new JSONArray(redisUtil.get(key));
            result.setCode(200);
            result.setSuccess(true);
            result.setResult(jsonArray);
            return result;
        }

        String path = "https://jmgjyyjgcx.api.bdymkt.com/gjyycx/oil/price-his-inter/query";
        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.POST, path);
        request.setCredentials("2a1650d2b63c4a038b218c66e4157415", "52b2b81c99384292813f53f44fde5aca");

        // 设置header参数
        request.addHeaderParameter("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

        // 计算一周前的日期
        LocalDate oneWeekAgo = currentDate.minusWeeks(1);

        // 设置jsonBody参数
        String jsonBody = "code=" + code
                + "&beginDate=" + oneWeekAgo.format(formatter)
                + "&endDate=" + currentDate.format(formatter);
        request.setJsonBody(jsonBody);

        ApiExplorerClient client = new ApiExplorerClient(new AppSigner());

        // 创建输出格式化器，格式化日期
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("MM.dd");

        try {
            ApiExplorerResponse response = client.sendRequest(request);
            // 返回结果格式为Json字符串
            JSONArray jsonArray = new JSONObject(response.getResult()).getJSONArray("data");
            for (int i = 0; i < jsonArray.size(); i++) {
                LocalDate date = LocalDate.parse(jsonArray.getJSONObject(i).getStr("day"), formatter);
                jsonArray.getJSONObject(i).set("dayStr", date.format(outputFormatter));
            }

            redisUtil.set(key, jsonArray.toString());

            result.setCode(200);
            result.setSuccess(true);
            result.setResult(jsonArray);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setSuccess(false);
            result.setMessage("服务器响应失败");
            return result;
        }
    }
}
